﻿using Caliburn.Micro;
using MusicExplorer.Common;
using MusicExplorer.Model;
using MusicExplorer.Repository;
using MusicExplorer.Repository.Interfaces;
using MusicExplorer.ViewModels.Wrappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;

namespace MusicExplorer.ViewModels
{
    public sealed class TracksPageViewModel : PageViewModelBase
    {
        private QueryGroup m_group;
        private readonly DispatcherTimer m_timer;
        private bool m_inSearch;

        private TracksCollection m_tracks;

        public TracksPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            m_inSearch = false;
            m_timer = new DispatcherTimer();
            m_timer.Interval = TimeSpan.FromMilliseconds(100);
            m_timer.Tick += (s, e) =>
            {
                m_timer.Stop();
                if (!m_inSearch) HideLoading();
            };
        }

        protected override void OnInitialize()
        {
            ShowLoading();

            m_group = ((TracksPageNavigationObject)Parameter).Group;

            try
            {
                m_tracks = new TracksCollection(this, m_group, m_tokenSource.Token);
                m_tracks.StartSearching += (s, e) =>
                    {
                        m_inSearch = true;
                        ShowLoading();
                        m_timer.Start();
                    };
                m_tracks.EndSearching += (s, e) =>
                {
                    m_inSearch = false;
                    m_timer.Start();
                };
                NotifyOfPropertyChange(() => Tracks);
            }
            catch(Exception ex)
            {
                if (!m_tokenSource.IsCancellationRequested)
                    RedirectToError(ex);
            }

            Title = m_group.Name;

            HideLoading();
        }

        public TracksCollection Tracks { get { return m_tracks; } }

        public void OpenMedia(SelectionChangedEventArgs selection)
        {
            if (selection != null && selection.AddedItems.Count == 1)
            {
                var track = selection.AddedItems[0] as TrackTileViewModel;
                Root.SelectedTrack = track;
            }
        }
    }
}
